package com.superb.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.superb.dto.Login;
import com.superb.entity.User;
import com.superb.service.UserService;
//import com.superb.util.JwtUtils;
import com.superb.util.Result;
//import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Superb
 * @date 2020/11/8 - 14:26
 * @E_mail superb12580@163.com
 */
@RestController
public class AccountController {

    @Autowired
    private UserService userService;
//    @Autowired
//    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody Login login, HttpServletResponse response){
        //判断用户是否存在
        User user = userService.getOne(new QueryWrapper<User>().eq("username", login.getUsername()));
        if (user == null)
            return Result.fail("用户名不存在");

        //判断密码是否正确
        if (!user.getPassword().equals(SecureUtil.md5(login.getPassword()))){
            return Result.fail("密码不正确");
        }

//        //根据用户id生成jwt
//        String jwt = jwtUtils.generateToken(user.getId());
//        response.setHeader("Authorization",jwt);
//        response.setHeader("Access-control-Expose-Headers", "Authorization");



        //返回用户信息
        return Result.success("登录成功", MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()
        );
    }

    /**
     * 注销
     *
     * @return
     */
    //@RequiresAuthentication //登录后才能访问该接口
//    @GetMapping("/logout")
//    public Result logout() {
//        SecurityUtils.getSubject().logout();
//        return Result.success("注销成功");
//    }
}
